package com.googlecode.garbagecan.cxfstudy.filetransfer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class FileTransferServiceImpl implements FileTransferService {

	public void uploadFile(FileTransferObject fto) throws FileTransferException {
		OutputStream os = null;
		
		try {
			if (fto.getPosition() != 0) {
				os = FileUtils.openOutputStream(new File(fto.getServerFile()), true);
			} else {
				os = FileUtils.openOutputStream(new File(fto.getServerFile()), false);
			}
			os.write(fto.getBytes());
		} catch(IOException e) {
			throw new FileTransferException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(os);
		}
	}

	public FileTransferObject downloadFile(FileTransferObject fto) throws FileTransferException {
		InputStream is = null;
		
		try {
			is = new FileInputStream(fto.getServerFile());
			is.skip(fto.getPosition());
			byte[] bytes = new byte[1024 * 1024];
			int size = is.read(bytes);
			if (size > 0) {
				byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);
				fto.setBytes(fixedBytes);
			} else {
				fto.setBytes(new byte[0]);
			}
		} catch(IOException e) {
			throw new FileTransferException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(is);
		}
		return fto;
	}
	
	public MyFile[] list(String dir) throws FileTransferException {
		File[] files = new File(dir).listFiles();
		MyFile[] myFiles = new MyFile[files.length];
		for (int i = 0; i < files.length; i++) {
			MyFile myFile = new MyFile();
			myFile.setName(files[i].getName());
			myFile.setPath(files[i].getPath());
			myFile.setFile(files[i].isFile());
			myFile.setDirectory(files[i].isDirectory());
			myFiles[i] = myFile;
		}
		return myFiles;
	}
}
